﻿using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using Kyoh.App.Crawler.Plugin;
using Kyoh.Lib.Plugin;
using System.Runtime.InteropServices;

namespace Kyoh.App.Crawler.Contents
{
    /// <summary>リダイレクトの管理を行うクラス。</summary>
    class Redirects : PluginManager<IRedirect>, IRedirect
    {
        public Task<string> ParseAsync(string uri)
        {
            return Task<string>.Factory.StartNew(() =>
                Parse(uri));
        }

        #region IPlugin メンバー
        [Browsable(false)]
        public bool SupportsPreference { get { return false; } }
        [Browsable(false)]
        public Type PreferenceType { get { return null; } }
        #endregion

        #region IRedirect メンバー
        public bool Supports(string uri)
        {
            foreach (var info in this)
            {
                try
                {
                    if (info.Supports(uri))
                        return true;
                }
                catch (Exception exc)
                {
                    //TODO:
                    Debug.WriteLine(exc);
                }
            }
            return false;
        }
        public string Parse(string uri)
        {
            return Parse(uri, new StringDictionary(), Properties.Settings.Default.MaximumAutomaticRedirections);
        }
        private string Parse(string uri, StringDictionary passed, int remainingAutomaticRedirections)
        {
            foreach (var info in this)
            {
                try
                {
                    if (info.Supports(uri))
                    {
                        string ret = info.Parse(uri);
                        if (ret != null && !passed.ContainsKey(ret) && remainingAutomaticRedirections-- > 0)
                        {
                            passed.Add(ret, string.Empty);
                            return Parse(ret, passed, remainingAutomaticRedirections);
                        }
                    }
                }
                catch (Exception exc)
                {
                    //TODO:
                    Debug.WriteLine(exc);
                }
            }
            return uri;
        }
        #endregion

        public string Author { get { return "kyoh"; } }
        public string Description { get { return string.Empty; } }
        public Uri Uri { get { return new Uri("http://kyoh.net/"); } }

        public object Preferences
        {
            get { return null; }
            set { }
        }
        public string Name { get { return "Redirects"; } }
    }
}